<?php
namespace control;
/*
*资产负债表类
*/

class assetDebtClass extends adIndexClass
{
    private const page = 'assetDebt';
    private const title = '资产负债表';
    private const table = 'asset_debt';
    public bool $isExport = false;

    /**
     * 导入企业会计准则资产负债表
     */
//    public function importData()
//    {
//         $fomatArray = [];//导入数据格式同一为TYPE_STRING
//            foreach ($this->importFieldInit() as $value){
//                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
//            }
//            $data = $this->importHead(format: $fomatArray);
//        $x = 0;
//        foreach ($data as $i => $row) {
//                $cell = formSubArray($row);
//                $field = [
//                    'id' => self::getId(),
//                    "accountRule" => 'enterpriseRule',        //所属部门
//                    "type" => $cell[0],
//                    "name" => $cell[1],                //职位名称
//                    "list" => $cell[2],
//                    'direction'=>'+'
//                ];
//                insert(["table" => self::table.'_demo', "field" => $field]);
//                $x++;
//        }
//        $warn = "成功导入" . $x . "条数据，详情请查看日志！";
//        $_SESSION['warn'] = $warn;
//        header("Location:" . getenv("HTTP_REFERER"));
//        exit(0);
//    }

//    public function importData()
//    {
//         $fomatArray = [];//导入数据格式同一为TYPE_STRING
//            foreach ($this->importFieldInit() as $value){
//                $fomatArray[] = \Vtiful\Kernel\Excel::TYPE_STRING;
//            }
//            $data = $this->importHead(format: $fomatArray);
//        $x = 0;
//        foreach ($data as $i => $row) {
//            if ($i>0){
//                $cell = formSubArray($row);
//                if ($cell[2]){
//                    $subject = query('subject',"code = '$cell[2]' and coid = '".self::$coid."'");
//                    $field = [
//                        'id' => self::getId(),
//                        "accountRule" => 'enterpriseRule',        //所属部门
//                        "name" => $cell[1],
//                        'subjectName'=>$subject['name'],//职位名称
//                        "subjectCode" => $cell[2],
//                        'symbol'=>$cell[4],
//                        'rule'=>$cell[5]
//                    ];
//                    insert(["table" => 'asset_debt_formula_demo', "field" => $field]);
//                    $x++;
//                }
//            }
//        }
//        $warn = "成功导入" . $x . "条数据，详情请查看日志！";
//        $_SESSION['warn'] = $warn;
//        header("Location:" . getenv("HTTP_REFERER"));
//        exit(0);
//    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "会计期间" => text(array("name" => "month", 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
                ]
            ]
        ]);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        //$button = $this->upButton(array("title" => "导入", "fun" => "importData"));
        //控件
        if ($this->power(self::page, "export")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "print")) {
            $button .= "<span class='spanButton'  onclick=\"window.open('" . root . "control/adIndex.html?cla=" . self::page . "&fun=printPage')\">打印</span>";
        }
        //返回
        return $this->homeFun($this->searchExecute([
            'html' => $html,
            'layout' => 'pop',
            'toolButton' => $button,
            'option' => '{fixed:true}'
        ]));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        $month = $this->post('month');
        static::rSet(self::$stid . self::page . 'Month', $month);
        $text[] = array('', '', '', '', "style='width:300px'", '', '', '');
        // 月份选择器
        $monthSelector = componentClass::monthSelector(implode('~',[$month,$month]));
        $tr[] = array('资产', '行次', "期末余额", '年初余额', '负债和所有者权益', '行次', "期末余额", '年初余额'.$monthSelector['button']);

        $tr = array_merge($tr, $this->content($month)['tr']);
        //返回
        $json['html'] =
            "<div class='acct-main-container'>
                <form name='listForm'>" .
                    $this->tableMany(array("tr" => $tr, 'text' => $text)) .
                "</form>" .
                $monthSelector['html'].
            "</div>" .
            $this->js() .
            $this->css() .
            $this->tableCss() .
            clear;
        return json_encode($json, 320);
    }

    public function tableCss(): string
    {
        return <<<eof
<style>
#homeSearchHtml .tableMany tr td:nth-child(3),.tableMany tr td:nth-child(4),.tableMany tr td:nth-child(7),.tableMany tr td:nth-child(8){
  text-align: right;
}
#homeSearchHtml  .tableMany thead tr td{text-align: center !important;}
.tableMany td:nth-child(1) {
    width: auto;
}
.tableMany td:nth-child(1) {
    width: auto;
}
</style>
eof;

    }

    /**
     * 公式按钮
     */
    public static function formulaString($name): string
    {
        return "<span class='del-row-button hide' style='margin-left:10px' onclick=\"layer('" . self::page . "','formula',{name:'" . $name . "'})\">公式</span>";
    }

    public function content($month): array
    {
        //获取查询结果
        $where = "coid = '" . self::$coid . "'";
        $result = find(array("table" => self::table, "where" => $where . " and type ='流动资产' order by list"));
        //获取表头
        $tr = [];

        $list = 0;
        $leftBalanceTotal = [
            '流动资产' => 0,
            '非流动资产' => 0,
        ];
        $leftPreBalanceTotal = [
            '流动资产' => 0,
            '非流动资产' => 0,
        ];
        $rightBalanceTotal = [
            '流动负债' => 0,
            '非流动负债' => 0,
            '所有者权益(或股东权益)' => 0
        ];
        $rightPreBalanceTotal = [
            '流动负债' => 0,
            '非流动负债' => 0,
            '所有者权益(或股东权益)' => 0
        ];
        $accountRule = companyClass::returnRule(1);
        if ($accountRule == 'smallEnterpriseRule') {
            $addInt = 30;
            //小企业会计准则2013
            //获取记录
            foreach ($result['array'] as $index => $array) {
                //列表控件
                $dominate = self::formulaString($array['name']);
                if ($index == 0) {
                    $tr[] = ["<span style='font-weight: bold'>流动资产：</span>", ' ', ' ', ' ', "<span style='font-weight: bold'>流动负债：</span>", ' ', ' ', ' '];
                }
                $list = $index + $addInt + 1;
                $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                $rightName = "&emsp;" . $right['name'];
                $dominateRight = self::formulaString($right['name']);
                $rightBalance = $this->balance($right['name'], $month);
                $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                if ($array['name'] == '在产品') {
                    $dominateRight = '';
                    $rightName = "&emsp;流动负债合计";
                    $right['list'] = 41;
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债']);
                }
                if ($array['name'] == '库存商品') {
                    $dominateRight = '';
                    $rightName = "<span style='font-weight: bold'>非流动负债：</span>";
                    $right['list'] = ' ';
                    $addInt = 29;
                    $rightBalanceMoney = ' ';
                    $rightPreBalanceMoney = ' ';
                    $rightBalance['balance'] = $rightBalance['preBalance'] = 0;
                }
                $leftName = $array['name'];
                if ($array['pid']) {
                    $leftName = "&emsp;" . ($array['name'] == '原材料' ? "其中：原材料" : $array['name']);
                }
                $leftName = "&emsp;" . $leftName;
                $leftBalance = $this->balance($array['name'], $month);
//            if ($array['name'] =='其他流动资产'){
//                $leftBalance['balance'] = $leftBalance['preBalance'] =0;
//            }
                $tr[] = [
                    $leftName . $dominate,
                    $array['list'],
                    $this->fontColor($leftBalance['balance']),
                    $this->fontColor($leftBalance['preBalance']),
                    $rightName . $dominateRight,
                    $right['list'],
                    $rightBalanceMoney,
                    $rightPreBalanceMoney,
                ];

                //合计
                if (empty($array['pid'])) {
                    $leftBalanceTotal[$array['type']] += $leftBalance['balance'];
                    $leftPreBalanceTotal[$array['type']] += $leftBalance['preBalance'];
                }

                if ($right['type']) {
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                }
                if (!isset($result['array'][$index + 1]['name'])) {

                    $list = $index + $addInt + 2;
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];

                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    $dominateRight = self::formulaString($right['name']);
                    $tr[] = [
                        "&emsp;" . '流动资产合计',
                        $array['list'] + 1,
                        $this->fontColor($leftBalanceTotal['流动资产']),
                        $this->fontColor($leftPreBalanceTotal['流动资产']),
                        "&emsp;" . $right['name'] . $dominateRight,
                        $right['list'],
                        $this->fontColor($rightBalance['balance']),
                        $this->fontColor($rightBalance['preBalance']),
                    ];
                }
            }

            $result = find(array("table" => self::table, "where" => $where . " and type ='非流动资产' order by list"));
            foreach ($result['array'] as $index => $array) {
                $dominate = self::formulaString($array['name']);
                $right['name'] = '';
                $right['list'] = '';
                if ($index == 0) {
                    $list += 1;
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $dominateRight = self::formulaString($right['name']);
                    $rightBalance = $this->balance($right['name'], $month);
                    $tr[] = ["<span style='font-weight: bold'>非流动资产：</span>", ' ', ' ', ' ', "&emsp;" . $right['name'] . $dominateRight, $right['list'], $this->fontColor($rightBalance['balance']), $this->fontColor($rightBalance['preBalance'])];
                    if ($right['type']) {
                        //初始化右边的合计
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    }
                }
                $list += 1;
                if ($array['list'] < 18) {
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                }
                $rightBalance = $this->balance($right['name'], $month);
                $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                $rightName = "&emsp;" . $right['name'];
                if ($array['name'] == '长期债券投资') {
                    $rightName = "&emsp;非流动负债合计";
                    $right['list'] = 46;
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['非流动负债']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['非流动负债']);
                }
                if ($array['name'] == '长期股权投资') {
                    $rightName = "<span style='font-weight: bold'>负债合计</span>";
                    $right['list'] = 47;
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债'] + $rightBalanceTotal['非流动负债']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['非流动负债']);
                }
                if ($array['name'] == '生产性生物资产') {
                    $rightName = "<span style='font-weight: bold'>所有者权益(或股东权益)：</span>";
                    $right['list'] = ' ';
                }
                if ($array['list'] >= 25) {
                    $addInt = 23;
                    $list = $addInt + $array['list'];
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightName = "&emsp;" . $right['name'];
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                }
                if ($right['type']) {
                    //初始化右边的合计
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    $dominateRight = self::formulaString($right['name']);
                } else {
                    $dominateRight = '';
                }
                $leftName = "&emsp;" . $array['name'];
                $leftBalance = $this->balance($array['name'], $month);
                if (!in_array($array['name'], ['固定资产账面价值'])) {
                    $leftBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftBalanceTotal[$array['type']] + $leftBalance['balance'] : $leftBalanceTotal[$array['type']] - $leftBalance['balance'];
                    $leftPreBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftPreBalanceTotal[$array['type']] + $leftBalance['preBalance'] : $leftPreBalanceTotal[$array['type']] - $leftBalance['preBalance'];
                }
                $tr[] = [
                    $leftName . $dominate,
                    $array['list'],
                    $this->fontColor($leftBalance['balance']),
                    $this->fontColor($leftBalance['preBalance']),
                    $rightName . $dominateRight,
                    $right['list'] ?: ' ',
                    $rightBalanceMoney,
                    $rightPreBalanceMoney
                ];
                if (!isset($result['array'][$index + 1]['name'])) {
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['所有者权益(或股东权益)']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['所有者权益(或股东权益)']);
                    $tr[] = [
                        "&emsp;" . '非流动资产合计',
                        $array['list'] + 1,
                        $this->fontColor($leftBalanceTotal['非流动资产']),
                        $this->fontColor($leftPreBalanceTotal['非流动资产']),
                        "&emsp;" . '所有者权益(或股东权益)合计',
                        $array['list'] + $addInt + 1,
                        $rightBalanceMoney,
                        $rightPreBalanceMoney
                    ];

                    $tr[] = [
                        "<span style='font-weight: bold'>资产总计</span>",
                        $array['list'] + 2,
                        $this->fontColor($leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产']),
                        $this->fontColor($leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产']),
                        "<span style='font-weight: bold'>负债和所有者权益(或股东权益)总计</span>",
                        $array['list'] + $addInt + 2,
                        $this->fontColor($rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)']),
                        $this->fontColor($rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']),
                    ];
                }
            }
        } elseif ($accountRule == 'enterpriseRule') {
            $addInt = 31;
            //企业会计准则2007
            foreach ($result['array'] as $index => $array) {
                //列表控件
                $dominate = self::formulaString($array['name']);
                if ($index == 0) {
                    $tr[] = ["<span style='font-weight: bold'>流动资产：</span>", ' ', ' ', ' ', "<span style='font-weight: bold'>流动负债：</span>", ' ', ' ', ' '];
                }
                $list = $index + $addInt + 1;
                $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                $rightName = "&emsp;" . $right['name'];
                $dominateRight = self::formulaString($right['name']);
                $rightBalance = $this->balance($right['name'], $month);
                $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                $leftName = $array['name'];
                $leftBalance = $this->balance($array['name'], $month);
                $tr[] = [
                    $leftName . $dominate,
                    $array['list'],
                    $this->fontColor($leftBalance['balance']),
                    $this->fontColor($leftBalance['preBalance']),
                    $rightName . $dominateRight,
                    $right['list'],
                    $rightBalanceMoney,
                    $rightPreBalanceMoney,
                ];

                //合计
                if (empty($array['pid'])) {
                    $leftBalanceTotal[$array['type']] += $leftBalance['balance'];
                    $leftPreBalanceTotal[$array['type']] += $leftBalance['preBalance'];
                }

                if ($right['type']) {
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                }
                if (!isset($result['array'][$index + 1]['name'])) {

                    $list = $index + $addInt + 2;
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];

                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    $dominateRight = self::formulaString($right['name']);
                    $tr[] = [
                        "&emsp;" . '流动资产合计',
                        $array['list'] + 1,
                        $this->fontColor($leftBalanceTotal['流动资产']),
                        $this->fontColor($leftPreBalanceTotal['流动资产']),
                        "&emsp;" . $right['name'] . $dominateRight,
                        $right['list'],
                        $this->fontColor($rightBalance['balance']),
                        $this->fontColor($rightBalance['preBalance']),
                    ];
                    $tr[] = [
                        ' ',
                        ' ',
                        ' ',
                        ' ',
                        "&emsp;" . '流动负债合计',
                        44,
                        $this->fontColor($rightBalanceTotal['流动负债']),
                        $this->fontColor($rightPreBalanceTotal['流动负债']),
                    ];
                }
            }
            $result = find(array("table" => self::table, "where" => $where . " and type ='非流动资产' order by list"));
            foreach ($result['array'] as $index => $array) {
                $dominate = self::formulaString($array['name']);
                $right['name'] = '';
                $right['list'] = '';
                if ($index == 0) {
                    $list += 1;
                    $tr[] = ["<span style='font-weight: bold'>非流动资产：</span>", ' ', ' ', ' ', "<span style='font-weight: bold'>非流动负债：</span>", ' ', ' ', ' ',];
                }
                $list += 1;
                if ($array['list'] < 21) {
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                }
                $rightBalance = $this->balance($right['name'], $month);
                $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                $rightName = "&emsp;" . $right['name'];
                if ($array['list'] == 21) {
                    $rightName = "&emsp;非流动负债合计";
                    $right['list'] = 53;
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['非流动负债']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['非流动负债']);
                }
                if ($array['list'] == 22) {
                    $rightName = "<span style='font-weight: bold'>负债合计</span>";
                    $right['list'] = 54;
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债'] + $rightBalanceTotal['非流动负债']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['非流动负债']);
                }
                if ($array['list'] == 23) {
                    $rightName = "<span style='font-weight: bold'>所有者权益(或股东权益)：</span>";
                    $right['list'] = ' ';
                }
                if ($array['list'] >= 24) {
                    $list = $addInt + $array['list'];
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightName = "&emsp;" . $right['name'];
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                }
                if ($right['type']) {
                    //初始化右边的合计
                    $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                    $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    $dominateRight = self::formulaString($right['name']);
                } else {
                    $dominateRight = '';
                }
                $leftName = "&emsp;" . $array['name'];
                $leftBalance = $this->balance($array['name'], $month);
                if (!in_array($array['name'], ['固定资产账面价值'])) {
                    $leftBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftBalanceTotal[$array['type']] + $leftBalance['balance'] : $leftBalanceTotal[$array['type']] - $leftBalance['balance'];
                    $leftPreBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftPreBalanceTotal[$array['type']] + $leftBalance['preBalance'] : $leftPreBalanceTotal[$array['type']] - $leftBalance['preBalance'];
                }
                $tr[] = [
                    $leftName . $dominate,
                    $array['list'],
                    $this->fontColor($leftBalance['balance']),
                    $this->fontColor($leftBalance['preBalance']),
                    $rightName . $dominateRight,
                    $right['list'] ?: ' ',
                    $rightBalanceMoney,
                    $rightPreBalanceMoney
                ];
                if (!isset($result['array'][$index + 1]['name'])) {
                    $rightBalanceMoney = $this->fontColor($rightBalanceTotal['所有者权益(或股东权益)']);
                    $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['所有者权益(或股东权益)']);
                    $tr[] = [
                        "&emsp;" . '非流动资产合计',
                        $array['list'] + 1,
                        $this->fontColor($leftBalanceTotal['非流动资产']),
                        $this->fontColor($leftPreBalanceTotal['非流动资产']),
                        "&emsp;" . '所有者权益(或股东权益)合计',
                        $array['list'] + $addInt + 1,
                        $rightBalanceMoney,
                        $rightPreBalanceMoney
                    ];

                    $tr[] = [
                        "<span style='font-weight: bold'>资产总计</span>",
                        $array['list'] + 2,
                        $this->fontColor($leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产']),
                        $this->fontColor($leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产']),
                        "<span style='font-weight: bold'>负债和所有者权益(或股东权益)总计</span>",
                        $array['list'] + $addInt + 2,
                        $this->fontColor($rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)']),
                        $this->fontColor($rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']),
                    ];
                }
            }
        }

        return [
            'tr' => $tr,
            'assetMoney' => $leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产'],
            'assetInitMoney' => $leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产'],
            'debtMoney' => $rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)'],
            'debtInitMoney' => $rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']
        ];
    }

    public function css()
    {
        return <<<eof
<style>
.tableMany{
  table-layout: fixed;
}
.table_many_shell > .tableMany td{
   white-space:normal;
}
.tableMany td:nth-child(1) {
    width: auto;
}
</style>
eof;

    }

    private function js()
    {
        return <<<eof
<script>
$(".tableMany tr").hover(function(){
    $(this).find(".del-row-button").show();
},function(){
      $(this).find(".del-row-button").hide();
});
function delThis(e,id){
     $.post(root+'control/adIndex.html?cla=assetDebt&fun=delRow',{id:id},function(res) {
       if (res.warn ===2){
          $(e).parent().parent().remove();
           return true;
       }
       msg(res.warn,'error')
    },'json')
}
function addRow(){
    $.post(root+'control/adIndex.html?cla=assetDebt&fun=addRow',$("[name='formulaForm']").serialize(),function(res) {
       if (res.warn ===2){
           $("#formula .tableMany tbody").append(res.html);
           return true;
       }
       msg(res.warn,'error')
    },'json')
}
</script>
eof;

    }

    public function formula(): bool|string
    {
        $name = $this->post('name');
        $tr[] = ['科目名称', '运算符号', '取数规则', '操作'];
        $all = find(array('table' => 'asset_debt_formula', 'where' => "name = '$name' and coid = '" . self::$coid . "' order by list "));
        foreach ($all['array'] as $array) {
            $subject = query('subject', "id = '$array[subjectId]'");
            $tr[] = [$subject['code'].'-'.$subject['name'], $array['symbol'], $array['rule'], "<span class='del-row-button' onclick=\"delThis(this,'$array[id]')\">删除</span>"];
        }
        $symbol = select(array('name' => 'symbol', 'class' => 'select', 'option' => ['+', '-'], 'value' => '+'));
        $rule = select(array('name' => 'rule', 'class' => 'select', 'option' => ['余额'], 'value' => '余额'));
        $subjectSelect = componentClass::subjectSelect();
        $html = <<<eof
<form name="formulaForm">
    <div class="search" style="padding: 0 0 10px 0;">科目：$subjectSelect&emsp;&emsp;运算符号：{$symbol}&emsp;&emsp;取值：$rule&emsp;&emsp;
        <input name="assetName" type="hidden" value="$name">
        <input type="button" onclick="addRow()" class="searchSub" value="添加">
    </div>
</form>
eof;

        $html = "<div style='padding: 10px 10px 0 10px' id='formula'>" . $html . $this->tableMany(['tr' => $tr, 'end' => true]) . "</div>";
        return $this->layer(array("title" => "公式-".$name, "height" => 500, 'width' => 1000, "html" => $html, "button" => false));
    }

    public function addRow()
    {

        $field = [
            'id' => suiji(),
            'coid' => self::$coid,
            'name' => $this->post('assetName'),
            'symbol' => $this->post('symbol'),
            'subjectId' => $this->post('subjectId'),
            'rule' => $this->post('rule'),
        ];
        $annotation = [
            'id' => 'ID',
            'coid' => '账套ID',
            'name' => '名称',
            'symbol' => '运算符号',
            'subjectId' => '科目',
            'rule' => '取值',
        ];
        $rules = [
            'id' => 'required',
            'coid' => 'required',
            'name' => 'required',
            'symbol' => 'required',
            'subjectId' => 'required',
            'rule' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        } elseif (static::total(array('table' => 'asset_debt_formula', 'where' => "name = '$field[name]' and coid = '" . self::$coid . "' and subjectId = '$field[subjectId]'")) > 0) {
            $json['warn'] = '已存在此科目';
        } else {
            $json['warn'] = static::insert(["table" => 'asset_debt_formula', "field" => $field]);
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "," . $field['name'] . '的科目：' . subjectClass::getName($field['subjectId']);
                $this->logText(["type" => self::page, "text" => $text]);
                $subject = query('subject', "id = '$field[subjectId]'");
                //返回
                $json['warn'] = 2;
                $json['html'] = $this->tableMany([
                    'tr' => [
                        [$subject['code'].'-'.$subject['name'], $field['symbol'], $field['rule'], "<span class='del-row-button' onclick=\"delThis(this,'$field[id]')\">删除</span>"]
                    ],
                    'thead' => false,
                ]);
            }
        }
        resp:
        return json_encode($json, 320);
    }

    public function delRow()
    {
        $id = $this->post('id');
        if (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $info = query('asset_debt_formula', "id = '$id'");
            $json['warn'] = delete(array('table' => 'asset_debt_formula', 'where' => "id = '$id'"));
            if ($json['warn'] == '删除成功') {
                $text = $this->control['name'] . "删除了" . self::title . "," . $info['name'] . '的科目：' . subjectClass::getName($info['subjectId']);
                $this->logText(["type" => self::page, "text" => $text]);
                $json['warn'] = 2;
            }
        }
        return json_encode($json, 320);
    }

    /**
     * 设置字体颜色
     */
    public function fontColor($num): string
    {
        if ($this->isExport) {
            return $num == 0 ? ' ' : $num;
        } else {
            if ($num < 0) {
                return "<span style='color: #fd5055'>" . number_format($num, 2) . "</span>";
            }
            return $num == 0 ? ' ' : number_format($num, 2);
        }
    }

    /**
     * 期末余额
     */
    public function balance($name, $month): array
    {
        $company = query('company', "coid = '" . self::$coid . "'");
        $subjectBalance = new subjectBalanceClass();
        $all = find(array('table' => 'asset_debt_formula', 'where' => "name = '$name' and coid = '" . self::$coid . "' order by list"));
        $balance = 0;//期末余额
        $preBalance = 0;//年初余额
        $multObj = new multiColumnAccountClass();
        foreach ($all['array'] as $array) {
            $parent = query('subject', "id = '$array[subjectId]'");
            $columns = [];
            $multObj->loopSubjectIds($array['subjectId'], $columns);
            $childBalance = 0;
            $childdPreBalance = 0;
            foreach ($columns as $subjectId) {
                $result = $subjectBalance->balance($month, $subjectId);
                $childSubject = query('subject', "id = '$subjectId'");
                if ($parent['direction'] == $childSubject['direction']) {
                    $childBalance += $result['balance'];
                } else {
                    $childBalance -= $result['balance'];
                }
                if (date('Y', strtotime($month . '-01')) <= date('Y', strtotime($company['startDate'] . '-01'))) {
                    //科目期初
                    if ($childSubject['direction'] == '借') {
                        $yearMoney = $childSubject['loanMoney'] + $childSubject['initMoney'] - $childSubject['borrowMoney'];
                    } else {
                        $yearMoney = $childSubject['initMoney'] + $childSubject['borrowMoney'] - $childSubject['loanMoney'];
                    }
                    if ($parent['direction'] == $childSubject['direction']) {
                        $childdPreBalance += self::centToYuan($yearMoney);
                    } else {
                        $childdPreBalance -= self::centToYuan($yearMoney);
                    }

                } else {
                    //上一年期末余额
                    $endMonth = (date('Y', strtotime($month . '-01')) - 1) . '-12';
                    $result = $subjectBalance->balance($endMonth, $subjectId);
                    if ($parent['direction'] == $childSubject['direction']) {
                        $childdPreBalance += $result['balance'];
                    } else {
                        $childdPreBalance -= $result['balance'];
                    }
                }
            }
            switch ($array['rule']) {
                case '借方余额':
                case '贷方余额':
                default:
                    $balance = match ($array['symbol']) {
                        '-' => $balance - $childBalance,
                        default => $balance + $childBalance
                    };
                    $preBalance = match ($array['symbol']) {
                        '-' => $preBalance - $childdPreBalance,
                        default => $preBalance + $childdPreBalance
                    };
                    break;
            }

        }
        return ['balance' => $balance, 'preBalance' => $preBalance];
    }


    /**
     * 打印
     * @return string
     */
    public function printPage(): string
    {
        $month = static::rGet(self::$stid . self::page . 'Month');
        $days = date('t', strtotime($month));
        $month = date('Y年m月d日', strtotime($month . '-' . $days));
        $company = query('company', "coid = '" . self::$coid . "'");//公司名称
        $tr = $this->content($month)['tr'];
        $tempHtml = '';
        foreach ($tr as $array) {
            $tempHtml .= "<tr class='have_border'>";
            for ($i = 0; $i <= 7; $i++) {
                $tempHtml .= "<td>{$array[$i]}</td>";
            }
            $tempHtml .= "</tr>";
        }


        $divHtml = "
                 <div>
                      <div class='printTitle' style='font-weight: bold;height: 30px'>资产负债表</div>
                 </div>
                 <div class='table-top-title'><div style='flex: 1'>编制单位：$company[name]</div><div style='flex: 1;text-align: center'>$month</div><div style='flex: 1;text-align: right'>单位：元</div></div>
              <table class='printTable' style='font-size: 14px'  data-op-type='block-box'>
                <tbody class='nop-fill-box'>
               <tr class='have_border'>
                   <td>资产</td>
                   <td>行次</td>
                   <td>期末余额</td>
                   <td>年初余额</td>
                   <td width='150px'>负债和所有者权益</td>
                   <td>行次</td>
                   <td>期末余额</td>
                   <td>年初余额</td>
                </tr>
                $tempHtml
               </tbody>
              </table>
              <div class='table-top-title' style='margin-top: 5px'><div style='flex: 1'>法定代表人：</div><div style='flex: 1;'>主管会计工作负责人：</div><div style='flex: 1;'>会计机构负责人：</div></div>
            ";
        $html = <<<eof
                    <div id="content-box" style="display: none">
                        <div data-op-type='new-page'></div>
                    <!--    <div data-op-type="pendants">&lt;!&ndash; 定义页面部件（页眉/页脚/书签/水印背景等） &ndash;&gt;-->
                    <!--        <div class='pendant-title'>实发工资表</div>-->
                    <!--    </div>-->
                       $divHtml
                    </div>
                  <style>
                      .footer-ul-parent{float: right;margin-right: 10px}
                      .footer-ul li{margin-top: 10px}
                      .table-top-title{
                        height: 30px;
                        line-height: 30px;
                        font-size: 15px;
                        margin-top: 20px;
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                      }
                      .printTable tr td{white-space: nowrap}
                       .printTable tr td:nth-child(5){white-space: normal}
                      .printTable tr td:nth-child(3),.printTable tr td:nth-child(4),.printTable tr td:nth-child(7),.printTable tr td:nth-child(8){
  text-align: right;
}
.printTable tbody tr:nth-child(1) td{text-align: center !important;}
</style>
eof;
        $print = new printClass();

        return $print->showPrint($html, 'portrait', ['padding' => "5mm 5mm 5mm 5mm",'hidenPrice'=>1]);
    }

    /**
     * 导出
     */
    public function exportData()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        } else {
            $this->isExport = true;//导出需要去掉html标签
            $tr = [];
            $month = static::rGet(self::$stid . self::page . 'Month');
            $title = array('资产', '行次', "期末余额", '年初余额', '负债和所有者权益', '行次', "期末余额", '年初余额');
            //获取查询结果
            $where = "coid = '" . self::$coid . "'";
            $result = find(array("table" => self::table, "where" => $where . " and type ='流动资产' order by list"));
            //获取表头

            $list = 0;
            $leftBalanceTotal = [
                '流动资产' => 0,
                '非流动资产' => 0,
            ];
            $leftPreBalanceTotal = [
                '流动资产' => 0,
                '非流动资产' => 0,
            ];
            $rightBalanceTotal = [
                '流动负债' => 0,
                '非流动负债' => 0,
                '所有者权益(或股东权益)' => 0
            ];
            $rightPreBalanceTotal = [
                '流动负债' => 0,
                '非流动负债' => 0,
                '所有者权益(或股东权益)' => 0
            ];
            //获取记录
            $accountRule = companyClass::returnRule(1);
            if ($accountRule == 'smallEnterpriseRule') {
                $addInt = 30;
                foreach ($result['array'] as $index => $array) {
                    if ($index == 0) {
                        $tr[] = ["流动资产：", ' ', ' ', ' ', "流动负债：", ' ', ' ', ' '];
                    }
                    $list = $index + $addInt + 1;
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightName = " " . $right['name'];
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    if ($array['name'] == '在产品') {
                        $rightName = " 流动负债合计";
                        $right['list'] = 41;
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债']);
                    }
                    if ($array['name'] == '库存商品') {
                        $rightName = "非流动负债：";
                        $right['list'] = ' ';
                        $addInt = 29;
                        $rightBalanceMoney = ' ';
                        $rightPreBalanceMoney = ' ';
                        $rightBalance['balance'] = $rightBalance['preBalance'] = 0;
                    }
                    $leftName = $array['name'];
                    if ($array['pid']) {
                        $leftName = " " . ($array['name'] == '原材料' ? "其中：原材料" : $array['name']);
                    }
                    $leftName = " " . $leftName;
                    $leftBalance = $this->balance($array['name'], $month);

                    $tr[] = [
                        $leftName,
                        $array['list'],
                        $this->fontColor($leftBalance['balance']),
                        $this->fontColor($leftBalance['preBalance']),
                        $rightName,
                        $right['list'],
                        $rightBalanceMoney,
                        $rightPreBalanceMoney,
                    ];

                    //合计
                    if (empty($array['pid'])) {
                        $leftBalanceTotal[$array['type']] += $leftBalance['balance'];
                        $leftPreBalanceTotal[$array['type']] += $leftBalance['preBalance'];
                    }
                    if ($right['type']) {
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    }
                    if (!isset($result['array'][$index + 1]['name'])) {
                        $list = $index + $addInt + 2;
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                        $rightBalance = $this->balance($right['name'], $month);
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                        $tr[] = [
                            " " . '流动资产合计',
                            $array['list'] + 1,
                            $this->fontColor($leftBalanceTotal['流动资产']),
                            $this->fontColor($leftPreBalanceTotal['流动资产']),
                            " " . $right['name'],
                            $right['list'],
                            $this->fontColor($rightBalance['balance']),
                            $this->fontColor($rightBalance['preBalance']),
                        ];
                    }
                }

                $result = find(array("table" => self::table, "where" => $where . " and type ='非流动资产' order by list"));
                foreach ($result['array'] as $index => $array) {
                    $right['name'] = '';
                    $right['list'] = '';
                    if ($index == 0) {
                        $list += 1;
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                        $rightBalance = $this->balance($right['name'], $month);
                        $tr[] = ["非流动资产：", ' ', ' ', ' ', " " . $right['name'], $right['list'], $this->fontColor($rightBalance['balance']), $this->fontColor($rightBalance['preBalance'])];
                        if ($right['type']) {
                            //初始化右边的合计
                            $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                            $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                        }
                    }
                    $list += 1;
                    if ($array['list'] < 18) {
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    }
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    $rightName = " " . $right['name'];
                    if ($array['name'] == '长期债券投资') {
                        $rightName = " 非流动负债合计";
                        $right['list'] = 46;
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['非流动负债']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['非流动负债']);
                    }
                    if ($array['name'] == '长期股权投资') {
                        $rightName = "负债合计";
                        $right['list'] = 47;
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债'] + $rightBalanceTotal['非流动负债']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['非流动负债']);
                    }
                    if ($array['name'] == '生产性生物资产') {
                        $rightName = "所有者权益(或股东权益)：";
                        $right['list'] = ' ';
                    }
                    if ($array['list'] >= 25) {
                        $addInt = 23;
                        $list = $addInt + $array['list'];
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                        $rightBalance = $this->balance($right['name'], $month);
                        $rightName = " " . $right['name'];
                        $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                        $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    }
                    $leftName = " " . $array['name'];
                    $leftBalance = $this->balance($array['name'], $month);
                    if (!in_array($array['name'], ['固定资产账面价值'])) {
                        $leftBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftBalanceTotal[$array['type']] + $leftBalance['balance'] : $leftBalanceTotal[$array['type']] - $leftBalance['balance'];
                        $leftPreBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftPreBalanceTotal[$array['type']] + $leftBalance['preBalance'] : $leftPreBalanceTotal[$array['type']] - $leftBalance['preBalance'];
                    }
                    if ($right['type']) {
                        //初始化右边的合计
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    }
                    $tr[] = [
                        $leftName,
                        $array['list'],
                        $this->fontColor($leftBalance['balance']),
                        $this->fontColor($leftBalance['preBalance']),
                        $rightName,
                        $right['list'] ?: ' ',
                        $rightBalanceMoney,
                        $rightPreBalanceMoney
                    ];
                    if (!isset($result['array'][$index + 1]['name'])) {
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['所有者权益(或股东权益)']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['所有者权益(或股东权益)']);
                        $tr[] = [
                            " " . '非流动资产合计',
                            $array['list'] + 1,
                            $this->fontColor($leftBalanceTotal['非流动资产']),
                            $this->fontColor($leftPreBalanceTotal['非流动资产']),
                            " " . '所有者权益(或股东权益)合计',
                            $array['list'] + $addInt + 1,
                            $rightBalanceMoney,
                            $rightPreBalanceMoney
                        ];

                        $tr[] = [
                            "资产总计",
                            $array['list'] + 2,
                            $this->fontColor($leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产']),
                            $this->fontColor($leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产']),
                            "负债和所有者权益(或股东权益)总计",
                            $array['list'] + $addInt + 2,
                            $this->fontColor($rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)']),
                            $this->fontColor($rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']),
                        ];
                    }
                }
            } elseif ($accountRule == 'enterpriseRule') {
                $addInt = 31;
                foreach ($result['array'] as $index => $array) {
                    if ($index == 0) {
                        $tr[] = ["流动资产：", ' ', ' ', ' ', "流动负债：", ' ', ' ', ' '];
                    }
                    $list = $index + $addInt + 1;
                    $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    $rightName = " " . $right['name'];
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    $leftName = $array['name'];
                    $leftBalance = $this->balance($array['name'], $month);

                    $tr[] = [
                        $leftName,
                        $array['list'],
                        $this->fontColor($leftBalance['balance']),
                        $this->fontColor($leftBalance['preBalance']),
                        $rightName,
                        $right['list'],
                        $rightBalanceMoney,
                        $rightPreBalanceMoney,
                    ];

                    //合计
                    if (empty($array['pid'])) {
                        $leftBalanceTotal[$array['type']] += $leftBalance['balance'];
                        $leftPreBalanceTotal[$array['type']] += $leftBalance['preBalance'];
                    }
                    if ($right['type']) {
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    }
                    if (!isset($result['array'][$index + 1]['name'])) {
                        $list = $index + $addInt + 2;
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                        $rightBalance = $this->balance($right['name'], $month);
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                        $tr[] = [
                            " " . '流动资产合计',
                            $array['list'] + 1,
                            $this->fontColor($leftBalanceTotal['流动资产']),
                            $this->fontColor($leftPreBalanceTotal['流动资产']),
                            " " . $right['name'],
                            $right['list'],
                            $this->fontColor($rightBalance['balance']),
                            $this->fontColor($rightBalance['preBalance']),
                        ];
                        $tr[] = [
                            ' ',
                            ' ',
                            ' ',
                            ' ',
                            " " . '流动负债合计',
                            44,
                            $this->fontColor($rightBalanceTotal['流动负债']),
                            $this->fontColor($rightPreBalanceTotal['流动负债']),
                        ];
                    }
                }
                $result = find(array("table" => self::table, "where" => $where . " and type ='非流动资产' order by list"));
                foreach ($result['array'] as $index => $array) {
                    $right['name'] = '';
                    $right['list'] = '';
                    if ($index == 0) {
                        $list += 1;
                        $tr[] = ["非流动资产：", ' ', ' ', ' ', "非流动负债：", ' ', ' ', ' '];
                    }
                    $list += 1;
                    if ($array['list'] < 21) {
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                    }
                    $rightBalance = $this->balance($right['name'], $month);
                    $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                    $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    $rightName = " " . $right['name'];
                    if ($array['list'] == 21) {
                        $rightName = " 非流动负债合计";
                        $right['list'] = 46;
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['非流动负债']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['非流动负债']);
                    }
                    if ($array['list'] == 22) {
                        $rightName = "负债合计";
                        $right['list'] = 47;
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['流动负债'] + $rightBalanceTotal['非流动负债']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['非流动负债']);
                    }
                    if ($array['list'] == 23) {
                        $rightName = "所有者权益(或股东权益)：";
                        $right['list'] = ' ';
                    }
                    if ($array['list'] >= 24) {
                        $list = $addInt + $array['list'];
                        $right = query(self::table, "coid = '" . self::$coid . "' and list = $list");
                        $rightBalance = $this->balance($right['name'], $month);
                        $rightName = " " . $right['name'];
                        $rightBalanceMoney = $this->fontColor($rightBalance['balance']);
                        $rightPreBalanceMoney = $this->fontColor($rightBalance['preBalance']);
                    }
                    $leftName = " " . $array['name'];
                    $leftBalance = $this->balance($array['name'], $month);
                    if (!in_array($array['name'], ['固定资产账面价值'])) {
                        $leftBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftBalanceTotal[$array['type']] + $leftBalance['balance'] : $leftBalanceTotal[$array['type']] - $leftBalance['balance'];
                        $leftPreBalanceTotal[$array['type']] = $array['direction'] == '+' ? $leftPreBalanceTotal[$array['type']] + $leftBalance['preBalance'] : $leftPreBalanceTotal[$array['type']] - $leftBalance['preBalance'];
                    }
                    if ($right['type']) {
                        //初始化右边的合计
                        $rightBalanceTotal[$right['type']] += $rightBalance['balance'];
                        $rightPreBalanceTotal[$right['type']] += $rightBalance['preBalance'];
                    }
                    $tr[] = [
                        $leftName,
                        $array['list'],
                        $this->fontColor($leftBalance['balance']),
                        $this->fontColor($leftBalance['preBalance']),
                        $rightName,
                        $right['list'] ?: ' ',
                        $rightBalanceMoney,
                        $rightPreBalanceMoney
                    ];
                    if (!isset($result['array'][$index + 1]['name'])) {
                        $rightBalanceMoney = $this->fontColor($rightBalanceTotal['所有者权益(或股东权益)']);
                        $rightPreBalanceMoney = $this->fontColor($rightPreBalanceTotal['所有者权益(或股东权益)']);
                        $tr[] = [
                            " " . '非流动资产合计',
                            $array['list'] + 1,
                            $this->fontColor($leftBalanceTotal['非流动资产']),
                            $this->fontColor($leftPreBalanceTotal['非流动资产']),
                            " " . '所有者权益(或股东权益)合计',
                            $array['list'] + $addInt + 1,
                            $rightBalanceMoney,
                            $rightPreBalanceMoney
                        ];

                        $tr[] = [
                            "资产总计",
                            $array['list'] + 2,
                            $this->fontColor($leftBalanceTotal['流动资产'] + $leftBalanceTotal['非流动资产']),
                            $this->fontColor($leftPreBalanceTotal['流动资产'] + $leftPreBalanceTotal['非流动资产']),
                            "负债和所有者权益(或股东权益)总计",
                            $array['list'] + $addInt + 2,
                            $this->fontColor($rightBalanceTotal['非流动负债'] + $rightBalanceTotal['流动负债'] + $rightBalanceTotal['所有者权益(或股东权益)']),
                            $this->fontColor($rightPreBalanceTotal['非流动负债'] + $rightPreBalanceTotal['流动负债'] + $rightPreBalanceTotal['所有者权益(或股东权益)']),
                        ];
                    }
                }
            }

            $text = $this->control['name'] . "导出了资产负债表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $tr, "资产负债表.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }
}

